<template>
  <a-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
  >
    <!--部门树-->
    <template>
      <a-row>
        <a-col :span="15">
          <a-input-search
            placeholder="请输入名称"
            @change="onChange"
            v-if="visible"
          />
        </a-col>
        <a-col :span="8" v-if="benbuFlag != null">
          <a-checkbox
            @change="onCheckBoxChange"
            style="margin-left: 10px; margin-top: 4px"
            :checked="benbuFlagReal"
          >
            只选择本部
          </a-checkbox>
        </a-col>
        <a-col :span="8">
          <a-dropdown
            style="float: right"
            :trigger="['click']"
            placement="bottomCenter"
            v-if="multipleFlag"
          >
            <a-menu slot="overlay">
              <a-menu-item key="1" @click="switchCheckStrictly(1)"
                >父子关联</a-menu-item
              >
              <a-menu-item key="2" @click="switchCheckStrictly(2)"
                >取消关联</a-menu-item
              >
              <a-menu-item key="3" @click="checkALL">全部勾选</a-menu-item>
              <a-menu-item key="4" @click="cancelCheckALL"
                >取消全选</a-menu-item
              >
              <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
              <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
            </a-menu>
            <a-button>
              树操作
              <a-icon type="down" />
            </a-button>
          </a-dropdown>
        </a-col>
      </a-row>
      <template>
        <a-tree
          :multiple="multipleFlag"
          v-if="departTree.length"
          :checkable="multipleFlag"
          :checkStrictly="checkStrictly"
          @check="onCheck"
          @select="onSelect"
          @expand="onExpand"
          :selectable="!multipleFlag"
          :selectedKeys="checkedKeys"
          :expandedKeys="expandedKeys"
          v-model="checkedKeys"
          :treeData="departTree"
        />
      </template>
    </template>
    <template slot="footer">
      <a-button @click="handleCancel">关闭</a-button>
      <a-button @click="handleClear">清空并关闭</a-button>
      <a-button html-type="submit" @click="handleSubmit" type="primary"
        >确定
      </a-button>
    </template>
  </a-modal>
</template>

<script>
import { getDepartTree } from '@/api/api'

let expandedKeySource = []
let selectList = []
let selectParentList = []
export default {
  name: 'ProcurementMethodWindow',
  components: {},
  props: {
    multipleFlag: {
      type: Boolean,
      default: false,
    },
    // 模式 0公司+部门 1公司 2项目
    orgFlag: {
      type: Number,
      default: -1,
    },
    powerFlag: {
      type: Boolean,
      default: true,
    },
    benbuFlag: {
      type: Boolean,
      default: null,
    },
    checkedDepartKeys: {
      type: String,
      default: '',
    },
    required: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      checkedKeys: [], // 存储选中的部门id
      departList: [], // 存储部门信息
      modalWidth: 400,
      title: '操作',
      visible: false,
      confirmLoading: false,
      headers: {},
      departTree: [],
      departListSys: [],
      expandedKeys: [],
      allTreeKeys: [],
      checkStrictly: false,
      benbuFlagReal: false,
      searchFlag: false,
    }
  },
  methods: {
    onCheckBoxChange(e) {
      this.benbuFlagReal = !this.benbuFlagReal
    },
    add(checkedDepartKeys) {
      this.departList = []
      this.queryDepartTree()
      this.visible = true
      this.$nextTick(() => {
        this.departList = []
        this.checkedKeys = checkedDepartKeys
        if (
          this.checkedKeys.length > 0 &&
          this.checkedKeys[0] !== undefined &&
          this.checkedKeys[0] !== null
        ) {
          if (!this.multipleFlag) {
            const depart = { key: '', value: '', title: '' }
            depart.key = this.checkedKeys[0]
            depart.title = this.$store.getters.getDepartmentName(
              this.checkedKeys[0]
            )
            this.departList.push(depart)
          } else {
            for (let i = 0; i < this.checkedKeys.length; i++) {
              const depart = { key: '', value: '', title: '' }
              depart.key = this.checkedKeys[i]
              depart.title = this.$store.getters.getDepartmentName(
                this.checkedKeys[i]
              )
              this.departList.push(depart)
            }
          }
        }
        this.benbuFlagReal = this.benbuFlag
        this.title = '请选择'
        switch (this.orgFlag) {
          case -1:
            this.title = this.title + '组织架构'
            break
          case 0:
            this.title = this.title + '公司/部门'
            break
          case 1:
            this.title = this.title + '公司'
            break
          case 2:
            this.title = this.title + '项目'
            break
          case 3:
            this.title = this.title + '项目/公司'
            break
          case 4:
            this.title = this.title + '部门'
            break
          case 5:
            this.title = this.title + '项目/部门'
            break
        }
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.departList = []
      this.checkedKeys = []
      this.departTree = []
    },
    handleSubmit() {
      const formData = {
        departIdList: this.departList,
        benbuFlag: this.benbuFlagReal,
      }
      this.departList = []
      this.$emit('ok', formData)
      this.confirmLoading = false
      this.close()
    },
    //
    handleCancel() {
      this.close()
    },
    handleClear() {
      this.departList = []
      const formData = {
        departIdList: this.departList,
        benbuFlag: this.benbuFlagReal,
      }
      this.$emit('ok', formData)
      this.confirmLoading = false
      this.close()
    },
    // 选择部门时作用的API
    onCheck(checkedKeys, info) {
      if (this.multipleFlag) {
        this.departList = []
        this.checkedKeys = checkedKeys
        const checkedNodes = info.checkedNodes
        for (let i = 0; i < checkedNodes.length; i++) {
          const de = checkedNodes[i].data.props
          const depart = { key: '', value: '', title: '' }
          depart.key = checkedNodes[i].data.key
          depart.value = de.value
          depart.title = de.title
          this.departList.push(depart)
        }
        console.log('onCheck', checkedKeys, info)
      }
    },
    onSelect(checkedKeys, info) {
      if (!this.multipleFlag) {
        this.departList = []
        this.checkedKeys = checkedKeys
        const checkedNodes = info.node.dataRef
        const depart = { key: '', value: '', title: '' }
        depart.key = checkedNodes.key
        depart.value = checkedNodes.value
        depart.title = checkedNodes.title
        this.departList.push(depart)
        console.log('onSelect', checkedKeys, info)
      }
    },
    // 展开tree方法
    onExpand(expandedK, expandedExtr) {
      this.expandedKeys = expandedK
    },
    // 获取部门树
    queryDepartTree() {
      console.log(this.multipleFlag)
      if (this.departTree.length === 0 || this.searchFlag) {
        getDepartTree({
          orgFlag: this.orgFlag,
          powerFlag: this.powerFlag,
        }).then((res) => {
          let treeLv2 = []
          if (res.result.data[0].children) {
            treeLv2 = res.result.data[0].children.map((item, index, arr) => {
              const treeLv2Tmp = item.key
              return treeLv2Tmp
            })
          }
          console.log(treeLv2)
          this.expandedKeys = treeLv2
          expandedKeySource = treeLv2
          this.departTree = res.result.data
          this.getAllKeys(this.departTree)
        })
        this.searchFlag = false
      }
    },
    // 获取所有的key
    getAllKeys(node) {
      node.map((item, index, arr) => {
        const node = {}
        node.id = item.id
        node.key = item.key
        node.title = item.title
        node.parentId = item.parentId
        this.departListSys.push(node)
        this.allTreeKeys.push(item.key)
        if (item.children && item.children.length > 0) {
          this.getAllKeys(item.children)
        }
      })
    },
    // 编辑情况下，禁止选择当前节点及其子节点
    diGuiTreeEdit(item, vals) {
      const data = item
      const treeAry = []
      for (const i in data) {
        const v = data[i]
        const node = {}
        if (v === null || v === undefined) {
        } else {
          if (v.children && v.children.length > 0) {
            if (v.title.indexOf(vals) > -1) {
              node.class = 'k-tree-select'
              selectList.push(v.parentId)
            } else {
              node.class = ''
            }
            node.key = v.key
            node.title = v.title
            node.parentId = v.parentId
            node.children = this.diGuiTreeEdit(v.children, vals)
            treeAry.push(node)
          } else {
            if (v.title.indexOf(vals) > -1) {
              node.class = 'k-tree-select'
              selectList.push(v.parentId)
              node.key = v.key
              node.title = v.title
              node.parentId = v.parentId
              treeAry.push(node)
            } else {
              node.class = ''
            }
          }
        }
      }
      return treeAry
    },
    // 获取父节点
    getParents(checkKey) {
      for (var i = 0; i < this.departListSys.length; i++) {
        const tmp = this.departListSys[i]
        if (tmp.id === parseInt(checkKey)) {
          selectParentList.push(tmp.key)
          if (this.checkHasParent(tmp.parentId)) {
            this.getParents(tmp.parentId)
          }
        }
      }
    },
    // 检查是否有父节点
    checkHasParent(checkKey) {
      for (var i = 0; i < this.departListSys.length; i++) {
        const tmp = this.departListSys[i]
        if (tmp.id === checkKey) {
          return tmp.id
        }
      }
    },
    // 搜索部门
    onChange(e) {
      let value = e.target.value
      if (!value) {
        this.searchFlag = true
        value = '@@@@'
      }

      this.queryDepartTree()
      selectList = []
      selectParentList = []
      this.departTree = this.diGuiTreeEdit(this.departTree, value)
      this.expandedKeys = []
      selectList.map((x) => {
        this.getParents(x)
        selectParentList.map((x) => {
          this.expandedKeys.push(x)
        })
      })
      console.log('this.expandedKeys:' + this.expandedKeys)
      if (this.expandedKeys.length === 0) {
        this.expandedKeys = expandedKeySource
      }
    },
    modalFormOk() {},
    expandAll() {
      this.expandedKeys = this.allTreeKeys
    },
    closeAll() {
      this.expandedKeys = []
    },
    checkALL() {
      this.checkedKeys = this.allTreeKeys
    },
    cancelCheckALL() {
      this.checkedKeys = []
    },
    switchCheckStrictly(v) {
      if (v === 1) {
        this.checkStrictly = false
      } else if (v === 2) {
        this.checkStrictly = true
      }
    },
  },
}
</script>
<style scoped>
.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}
</style>
